﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.IO;

namespace Simple.Storage.Serializer
{
    /// <summary>
    /// Implements a serializer for <see cref="Array"/> instances.
    /// </summary>
    public class ArraySerializer : AbstractSerializer
    {
        /// <summary>
        /// The parent serializer used to serialize the elements of the arrays.
        /// </summary>
        private readonly ISerializer parent;

        /// <summary>
        /// Initializes a new instance of the ArraySerializer class.
        /// </summary>
        /// <param name="parent">
        /// The parent serializer used to serialize the elements of the arrays.
        /// </param>
        public ArraySerializer(ISerializer parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            this.parent = parent;
        }

        /// <summary>
        /// Gets the parent serializer used to serialize the elements of the arrays.
        /// </summary>
        public ISerializer Parent
        {
            get { return this.parent; }
        }

        /// <summary>
        /// Implements the <see cref="ISerializer.CanSerialize"/> logic.
        /// </summary>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>
        /// <c>true</c> if the serializer can work with instances of <paramref name="type"/>;
        /// <c>false</c> otherwise.
        /// </returns>
        protected override bool InternalCanSerialize(Type type)
        {
            return type.IsArray
                && type.GetArrayRank() == 1
                && this.Parent.CanSerialize(type.GetElementType());
        }

        /// <summary>
        /// Implements the <see cref="ISerializer.CanWorkInPlace"/> logic.
        /// </summary>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>
        /// Always <c>false</c>.
        /// </returns>
        protected override bool InternalCanWorkInPlace(Type type)
        {
            return false;
        }

        /// <summary>
        /// Implements the serialization logic.
        /// </summary>
        /// <param name="writer">
        /// The writer - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="value">
        /// The value to serialize - guaranty to be not <c>null</c> and associated with
        /// the current serializer.
        /// </param>
        protected override void InternalSerialize(BinaryWriter writer, Type type, object value)
        {
            writer.Write(value != null);
            if (value != null)
            {
                Array array = value as Array;
                writer.Write(array.Length);

                for (int i = 0; i < array.Length; i++)
                {
                    this.Parent.Serialize(writer, type.GetElementType(), array.GetValue(i));
                }
            }
        }

        /// <summary>
        /// Implements the deserialization logic.
        /// </summary>
        /// <param name="reader">
        /// The reader - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>The deserialized value.</returns>
        protected override object InternalDeserialize(BinaryReader reader, Type type)
        {
            if (!reader.ReadBoolean())
            {
                // The stream contains a null value
                return null;
            }

            int length = reader.ReadInt32();
            Array array = Array.CreateInstance(type.GetElementType(), length);

            for (int i = 0; i < length; i++)
            {
                array.SetValue(this.Parent.Deserialize(reader, type.GetElementType()), i);
            }

            return array;
        }

        /// <summary>
        /// Implements the in-place deserialization logic - always raises an exception.
        /// </summary>
        /// <param name="reader">
        /// The reader - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="value">
        /// The container for the deserialized object - guaranty to be not <c>null</c>.
        /// </param>
        /// <exception cref="NotSupportedException">
        /// The in-place deserialization is not supported.
        /// </exception>
        protected override void InternalDeserialize(BinaryReader reader, Type type, object value)
        {
            throw new NotSupportedException();
        }
    }
}
